<?php

namespace App\Http\Controllers\Administrator\Game;

use App\Models\Def\MainGamePlat;
use App\Models\Log\AgentEarning;
use App\Models\Log\AgentWithdrawalFlow;
use App\Models\Log\Earning;
use App\Models\User;
use App\Models\Conf\Agent;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Dingo\Api\Routing\Helpers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;
use League\Flysystem\Config;
use Ramsey\Uuid\Uuid;
use Spatie\Permission\Models\Role;
use App\Http\Controllers\Controller;
use App\Http\Requests\Administrator\AgentRequest;

class AgentController extends Controller
{
    use Helpers;

    protected $roleName = 'agent_role';

    /**
     * gameapi
     * 2018/10/8 15:23
     * Administrator
     * index
     * Display a listing of the resource.
     * @param Request $request
     * @param Agent $agent
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function index(Request $request, Agent $agent)
    {
        $this->authorize('index', $agent);
        $agents = Agent::with('user')->paginate(config('administrator.paginate.limit'));
        return view('backend.game.agent.index', compact('agents'));
    }

    /**
     * gameapi
     * 2018/10/8 15:23
     * Administrator
     * create
     * Show the form for creating a new resource.
     * @param Agent $agent
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function create(Agent $agent)
    {
        $this->authorize('create', $agent);
        $plats = MainGamePlat::status()->get()->toArray();
        $agentPlats = [];
        return view('backend.game.agent.create_and_edit', compact('agent', 'plats', 'agentPlats'));
    }

    /**
     * gameapi
     * 2018/10/8 15:23
     * Administrator
     * store
     * Store a newly created resource in storage.
     * @param AgentRequest $request
     * @param Agent $agent
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function store(AgentRequest $request, Agent $agent)
    {
        $this->authorize('create', $agent);
        DB::beginTransaction();
        $data = $request->only(['name', 'rate', 'status', 'score_rate']);
        $userData = [
            'name' => $request->input('username'),
            'password' => $request->input('password'),
            'type' => 1
        ];
        $user = User::create($userData);
        $roles = Role::where('name', $this->roleName)->get()->pluck('id')->toArray();
        $user->assignRole($roles);
        $data = array_merge($data, ['user_id' => $user->id]);
        $agent = Agent::create($data);

        //创建网站平台关联
        if (!empty($request->plats)) {
            $agentPlats = array_combine($request->plats['id'], $request->plats['rate']);
        } else {
            $agentPlats = [];
        }
        $plats = MainGamePlat::all();
        $syncParams = [];
        foreach ($plats as $plat) {
            $status = in_array($plat->id, array_keys($agentPlats)) ? 1 : 0;
            if ($status) {
                $syncParams[$plat->id] = ['status' => $status, 'rate' => $agentPlats[$plat->id]];
                if (array_key_exists($plat->id, $agentPlats)) {
                    if ($agentPlats[$plat->id] < (float)$plat->rate) {
                        return Redirect::back()->withInput()->with('danger', $plat->main_game_plat_name . '比率不能小于系统加分比率' . $plat->rate);
                    }
                }
            } else {
                $syncParams[$plat->id] = ['status' => $status];
            }

        }

        $agent->mainGamePlats()->sync($syncParams);

        if (!empty($agent) && !empty($user)) {
            if (!$agent->status) {
                $user->delete();
            }
            DB::commit();
            return redirect()->route('agent.index')->with('success', '添加成功.');
        } else {
            DB::rollBack();
        }
    }

    /**
     * gameapi
     * 2018/10/5 21:21
     * Administrator
     * show
     * Display the specified resource.
     * @param $id
     */
    public function show(Agent $agent)
    {

    }

    /**
     * gameapi
     * 2018/10/8 15:24
     * Administrator
     * edit
     *
     * @param Agent $agent
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function edit(Agent $agent)
    {

        $this->authorize('update', $agent);
        $plats = MainGamePlat::status()->get()->toArray();
        $agentPlats = $agent->mainGamePlats()->where('conf_agent_main_game_plats.status', 1)->get()->toArray();
        return view('backend.game.agent.create_and_edit', compact('agent', 'plats', 'agentPlats'));
    }

    /**
     * gameapi
     * 2018/10/8 15:24
     * Administrator
     * update
     * Update the specified resource in storage.
     * @param AgentRequest $request
     * @param Agent $agent
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function update(AgentRequest $request, Agent $agent)
    {
        $this->authorize('update', $agent);
        $result = $agent->update($request->only(['is_external', 'status', 'rate', 'score_rate']));

        //创建网站平台关联
        if (!empty($request->plats)) {
            $agentPlats = array_combine($request->plats['id'], $request->plats['rate']);
        } else {
            $agentPlats = [];
        }
        $plats = MainGamePlat::all();
        $syncParams = [];
        foreach ($plats as $plat) {
            $status = in_array($plat->id, array_keys($agentPlats)) ? 1 : 0;
            if ($status) {
                $syncParams[$plat->id] = ['status' => $status, 'rate' => $agentPlats[$plat->id]];
                if (array_key_exists($plat->id, $agentPlats)) {
                    if ($agentPlats[$plat->id] < (float)$plat->rate) {
                        return Redirect::back()->withInput()->with('danger', $plat->main_game_plat_name . '比率不能小于系统加分比率' . $plat->rate);
                    }
                }
            } else {
                $syncParams[$plat->id] = ['status' => $status];
            }

        }

        $agent->mainGamePlats()->sync($syncParams);

        if ($agent->status) {
            $agent->user()->restore();
        } else {
            $agent->user()->delete();
        }
        if (!empty($result)) {
            return redirect()->route('agent.index')->with('success', '修改成功.');
        }
    }

    /**
     * gameapi
     * 2018/10/5 20:27
     * Administrator
     * destroy
     * Remove the specified resource from storage.
     * @param Agent $agent
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Exception
     */
    public function destroy(Agent $agent)
    {
        $this->authorize('destroy', $agent);
        DB::beginTransaction();
        if ($agent->user()->count() > 0) {
            $delUser = $agent->user()->forceDelete();
        } else {
            $delUser = true;
        }

        $delAgent = $agent->delete();

        if ($agent->mainGamePlats->count() > 0) {
            $delPlat = $agent->mainGamePlats()->detach();
        } else {
            $delPlat = true;
        }

        $sites = $agent->sites->count();
        if ($sites > 0) {
            DB::rollBack();
            return redirect()->route('agent.index')->with('danger', '删除失败！受影响行数为0！.');

        }

        if ($delAgent && $delUser && $delPlat) {
            DB::commit();
            return redirect()->route('agent.index')->with('success', '删除成功.');
        } else {
            DB::rollBack();
            return redirect()->route('agent.index')->with('danger', '删除失败！受影响行数为0！.');

        }
    }

    /**
     * gameapi
     * 2018/11/3 14:15
     * Administrator
     * batchDestroy
     * 批量删除
     * @param Request $request
     * @param Agent $agent
     * @return mixed
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function batchDestroy(Request $request, Agent $agent)
    {
        $this->authorize('destroy', $agent);

        $ids = json_decode($request->getContent(), true);

        if (!empty($ids)) {
            DB::beginTransaction();
            foreach ($ids as $id) {
                if (Agent::find($id)->user()->count() > 0) {
                    $user = Agent::find($id)->user()->forceDelete();
                } else {
                    $user = true;
                }

                if (Agent::find($id)->mainGamePlats->count() > 0) {
                    $plat = Agent::find($id)->mainGamePlats()->detach();
                } else {
                    $plat = true;
                }

                $sites = Agent::find($id)->sites->count();
                if ($sites > 0) {
                    DB::rollBack();
                    return $this->response->array([
                            'status_code' => 500,
                            'message' => '删除失败！受影响行数为0！请先删除代理所属网站！',
                        ]
                    );
                }

                if (!$user || !$plat) {
                    DB::rollBack();
                    return $this->response->array([
                            'status_code' => 500,
                            'message' => '删除失败！受影响行数为0！',
                        ]
                    );
                }
            }
            $result = Agent::whereIn('id', $ids)->delete();
            if ($result) {
                DB::commit();
                return $this->response->array([
                        'status_code' => 200,
                        'message' => '删除成功！受影响行数：' . $result,
                    ]
                );
            } else {
                DB::rollBack();
                return $this->response->array([
                        'status_code' => 500,
                        'message' => '删除失败！受影响行数为0！',
                    ]
                );
            }
        }
    }

    /**
     * gameapi
     * 2018/10/8 12:27
     * Administrator
     * getCurrentUserSite
     * 获取当前代理用户id
     * @return array
     */
    private function getCurrentUserAgent()
    {
        $user = \Auth::user();
        $type = $user->type;
        if ($type === 0) {
            $AgentIds = Agent::all()->pluck('id')->toArray();
        } elseif ($type == 1) {
            $AgentIds = $user->agent()->get()->pluck('id')->toArray();
        }

        return $AgentIds;
    }

    /**
     * gameapi
     * 2018/10/9 23:25
     * Administrator
     * withdrawal
     * 提款页面
     * @param Request $request
     * @param Agent $agent
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function withdrawal(Request $request, Agent $agent)
    {
        $this->authorize('withdrawal', $agent);
        $user = \Auth::user();
        $agentIds = $this->getCurrentUserAgent();
        $agentId = $request->agent_id ?? array_first($agentIds);
        $agents = Agent::whereIn('id', $agentIds)->get();
        $agent = $agentId ? Agent::find($agentId) : $user->agent;
        $payTypes = config('administrator.pay_types');
        return view('backend.game.agent.withdrawal', compact('agent', 'agents', 'payTypes'));
    }

    /**
     * gameapi
     * 2018/11/1 20:50
     * Administrator
     * withdrawalStore
     * 提款处理
     * @param Agent $agent
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Exception
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function withdrawalStore(Agent $agent, Request $request)
    {
        $this->authorize('withdrawal', $agent);
        $procedure_fee = 0;//手续费暂时默认为0
        $valid = $this->validate($request, [
                'money' => 'required|numeric|min:1|max:100000',
                'pay_type' => 'required|in:bankcard,alipay,wxpay',
                'account' => 'required|string|min:7|max:25|alpha_dash',
                'account_address' => 'nullable|string|min:2|max:32',
                'account_real_name' => 'required|string|min:2|max:6',
            ]
        );

        $agentWithdrawalFlow = AgentWithdrawalFlow::create([
                'agent_id' => $agent->id,
                'pay_type' => $valid['pay_type'],
                'transferid' => Uuid::uuid4()->getHex(),
                'account' => $valid['account'],
                'account_address' => $valid['account_address'],
                'account_real_name' => $valid['account_real_name'],
                'before_account_money' => $agent->money,
                'money' => $valid['money'],
                'procedure_fee' => $procedure_fee,
                'to_account_money' => $valid['money'] - $procedure_fee,
                'after_account_money' => $agent->money - $valid['money'],
            ]
        );

        if ($agentWithdrawalFlow) {
            return redirect()->route('agent.withdrawal', ['agent_id', $agent->id])->with('success', '提款申请成功.');
        } else {
            return redirect()->route('agent.withdrawal', ['agent_id', $agent->id])->with('message', '提款申请失败.');

        }

    }

    /**
     * gameapi
     * 2018/10/9 23:26
     * Administrator
     * withdrawalFlow
     * 提款日志
     * @param Request $request
     * @param Agent $agent
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function withdrawalFlow(Request $request, Agent $agent)
    {
        $this->authorize('withdrawal', $agent);
        $limit = $request->limit ?? config('administrator.paginate.limit');

        $startTime = empty($request->only('created_at_start')) ? Carbon::now()->startOfWeek()->toDateTimeString() : $request->created_at_start;
        $endTime = empty($request->only('created_at_end')) ? Carbon::now()->toDateTimeString() : $request->created_at_end;
        $where = [
            ['created_at', '>=', $startTime],
            ['created_at', '<=', $endTime],
        ];
        $params = [
            'created_at_start' => $startTime,
            'created_at_end' => $endTime,
            'transferid' => '',
            'agent_name' => '',
            'status' => ''
        ];

        if (isset($request->transferid)) {
            $where[] = ['transferid', '=', $request->transferid];
            $params['transferid'] = $request->transferid;
        }
        if (isset($request->status)) {
            $where[] = ['status', '=', $request->status];
            $params['status'] = (integer)$request->status;
        }

        $agentIds = $this->getCurrentUserAgent();

        //检查用户是否有权限查看此网站信息
        if (isset($request->agent_name)) {
            $agentId = Agent::where('name', $request->agent_name)->first()->id;
            if (!in_array($agentId, $agentIds)) {
                return redirect()->route('agent.withdrawal.flow')->with('message', '没有权限查看此代理信息.');
            }
        }
        $agent = Agent::find(array_first($agentIds));

        $withdrawalFlow = AgentWithdrawalFlow::whereIn('agent_id', $agentIds)
            ->where($where)
            ->whereHas(
                'agent', function ($query) use ($request, &$params) {
                if (isset($request->agent_name)) {
                    $params['agent_name'] = $request->agent_name;
                    $query->where('name', '=', $request->agent_name);
                }
            }
            )->with('agent', 'auditor');
        $withdrawalFlows = (clone $withdrawalFlow)->paginate((integer)$limit);

        $sumParams['money'] = (clone $withdrawalFlow)->sum('money');
        $sumParams['procedure_fee'] = (clone $withdrawalFlow)->sum('procedure_fee');
        $sumParams['to_account_money'] = (clone $withdrawalFlow)->sum('to_account_money');

        //dd($params);
        return view('backend.game.agent.withdrawal_flow', compact('withdrawalFlows', 'limit', 'params', 'sumParams', 'agent'));

    }

    /**
     * gameapi
     * 2018/10/9 23:26
     * Administrator
     * auditWithdrawalFlow
     * 审核提款申请
     * @param AgentWithdrawalFlow $agentWithdrawalFlow
     * @param Agent $agent
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function auditWithdrawalFlow(AgentWithdrawalFlow $agentWithdrawalFlow, Agent $agent)
    {
        $this->authorize('withdrawalAudit', $agent);
        $user = \Auth::user();
        if ($user->type != 0) {
            return redirect()->route('agent.withdrawal.flow')->with('message', '没有权限审核代理信息.');
        }
        $agentWithdrawalFlow->status = AgentWithdrawalFlow::STATUS_AUDIT;
        $agentWithdrawalFlow->save();
        return redirect()->route('agent.withdrawal.flow')->with('success', '审核成功.');
    }

    /**
     * gameapi
     * 2018/10/9 23:26
     * Administrator
     * cancelWithdrawalFlow
     * 注销申请
     * @param AgentWithdrawalFlow $agentWithdrawalFlow
     * @param Agent $agent
     * @return \Illuminate\Http\RedirectResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function cancelWithdrawalFlow(AgentWithdrawalFlow $agentWithdrawalFlow, Agent $agent)
    {
        $this->authorize('withdrawal', $agent);
        $agentWithdrawalFlow->status = AgentWithdrawalFlow::STATUS_CANCEL;
        $agentWithdrawalFlow->save();
        return redirect()->route('agent.withdrawal.flow')->with('success', '注销成功.');
    }


    /**
     * gameapi
     * 2018/10/10 1:22
     * Administrator
     * earningLog
     * 代理分红
     * @param Request $request
     * @param Agent $agent
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function earningLog(Request $request, Agent $agent)
    {
        $this->authorize('earning', $agent);
        $limit = $request->limit ?? config('administrator.paginate.limit');

        $startTime = empty($request->only('created_at_start')) ? Carbon::now()->startOfWeek()->toDateTimeString() : $request->created_at_start;
        $endTime = empty($request->only('created_at_end')) ? Carbon::now()->toDateTimeString() : $request->created_at_end;
        $where = [
            ['created_at', '>=', $startTime],
            ['created_at', '<=', $endTime],
        ];
        $params = [
            'created_at_start' => $startTime,
            'created_at_end' => $endTime,
            'agent_name' => '',
            'site_name' => '',
        ];


        $agentIds = $this->getCurrentUserAgent();
        //检查用户是否有权限查看此网站信息
        if (isset($request->agent_name)) {
            $agentId = Agent::where('name', $request->agent_name)->first()->id;
            if (!in_array($agentId, $agentIds)) {
                return redirect()->route('agent.earning')->with('message', '没有权限查看此代理信息.');
            }
        }
        $agent = Agent::find(array_first($agentIds));

        $earning = Earning::whereIn('agent_id', $agentIds)
            ->where($where)
            ->whereHas(
                'agent', function ($query) use ($request, &$params) {
                if (isset($request->agent_name)) {
                    $params['agent_name'] = $request->agent_name;
                    $query->where('name', '=', $request->agent_name);
                }
            }
            )
            ->whereHas(
                'site', function ($query) use ($request, &$params) {
                if (isset($request->site_name)) {
                    $params['site_name'] = $request->site_name;
                    $query->where('username', '=', $request->site_name);
                }
            }
            )
            ->with('agent', 'site');
        $earnings = (clone $earning)->paginate((integer)$limit);

        $sumParams['money'] = (clone $earning)->sum('money');
        $sumParams['earnings_money'] = (clone $earning)->sum('earnings_money');


        return view('backend.game.agent.earning', compact('earnings', 'limit', 'params', 'sumParams', 'agent'));
    }

}
